import {reqUserLogin,reqGetCode,reqUserRegister,reqUserInfo,reqLogOut} from '@/api'
import {setToken,getToken,removeToken} from '@/utils/token'
const actions = {
    // 获取验证码
    async userGetCode({commit},phone){
        let result = await reqGetCode(phone);
        if(result.code === 200){
            alert('感谢注册^_^！本次验证码为'+result.data+'\n\n请正确输入在指定位置完成注册！\n\n如非本人操作请忽略！！！')
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message))
        }
    },
    // 注册业务
    async userRegister({commit},data){
        let result = await reqUserRegister(data)
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message))
        }
    },
    // 登录业务
    async userLogin({commit},data){
        let result = await reqUserLogin(data)
        if(result.code === 200){
            commit("USERLOGIN",result.data.token)
            setToken(result.data.token)
            alert('登录'+result.message)
            return 'ok'
        }else{
            alert(result.message)
            return Promise.reject(new Error(result.message))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo()
        if(result.code === 200){
            commit("GETUSERINFO",result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error(result.message))
        }
    },
     // 退出登录
     async userLogOut({commit}){
        let result = await reqLogOut();
        if(result.code === 200){
            commit("USERLOGOUT")
        }
    }
}
const mutations = {
    USERLOGIN(state,value){
        state.token = value
    },
    GETUSERINFO(state,value){
        state.userInfo = value
    },
    USERLOGOUT(state){
        state.token = null
        state.userInfo = {}
        removeToken()
    }
}
const getters = {}
const state = {
    token:getToken(),
    userInfo:{}
}
export default {
    state,
    actions,
    mutations,
    getters
}